/**
 * Copyright (c) 2009 Muh Hon Cheng
 * 
 * Permission is hereby granted, free of charge, to any person obtaining 
 * a copy of this software and associated documentation files (the 
 * "Software"), to deal in the Software without restriction, including 
 * without limitation the rights to use, copy, modify, merge, publish, 
 * distribute, sublicense, and/or sell copies of the Software, and to 
 * permit persons to whom the Software is furnished to do so, subject 
 * to the following conditions:
 * 
 * The above copyright notice and this permission notice shall be 
 * included in all copies or substantial portions of the Software.
 * 
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT 
 * WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, 
 * INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF 
 * MERCHANTABILITY, FITNESS FOR A PARTICULAR 
 * PURPOSE AND NONINFRINGEMENT. IN NO EVENT 
 * SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE 
 * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, 
 * TORT OR OTHERWISE, ARISING FROM, OUT OF OR 
 * IN CONNECTION WITH THE SOFTWARE OR 
 * THE USE OR OTHER DEALINGS IN THE SOFTWARE.
 * 
 * @author 		Muh Hon Cheng <honcheng@gmail.com>
 * @copyright	2009	Muh Hon Cheng
 * @version
 * 
 */

package com.threeonemeeting.tab;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import android.app.Activity;
import android.app.ActivityGroup;
import android.app.LocalActivityManager;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.util.TypedValue;
import android.view.Display;
import android.view.Gravity;
import android.view.View;
import android.view.ViewGroup.LayoutParams;
import android.view.Window;
import android.view.WindowManager;
import android.widget.LinearLayout;
import android.widget.RadioGroup;

import com.threeonemeeting.Const;
import com.threeonemeeting.R;

public class ScrollableTabActivity extends ActivityGroup implements
		RadioGroup.OnCheckedChangeListener {

	protected LocalActivityManager activityManager;
	protected LinearLayout contentViewLayout;
	protected LinearLayout.LayoutParams contentViewLayoutParams;
	protected RadioGroup.LayoutParams buttonLayoutParams;
	protected RadioGroup bottomRadioGroup;
	protected List<Intent> intentList;
	protected List<String> titleList;
	protected List<Object> states;
	protected Map<Integer, View> mapTabView;
	protected SliderBarActivityDelegate delegate;

	protected IntentFilter changeTabIntentFilter;
	protected ChangeTabBroadcastReceiver changeTabBroadcastReceiver;

	protected int nCurrentIndex = 0;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

		activityManager = getLocalActivityManager();
		requestWindowFeature(Window.FEATURE_NO_TITLE);
		setContentView(R.layout.scrollable_tabhost);
		contentViewLayout = (LinearLayout) findViewById(R.id.contentViewLayout);

		bottomRadioGroup = (RadioGroup) findViewById(R.id.bottomMenu);
		bottomRadioGroup.setOnCheckedChangeListener(this);

		intentList = new ArrayList<Intent>();
		titleList = new ArrayList<String>();
		states = new ArrayList<Object>();
		mapTabView = new HashMap<Integer, View>();

		contentViewLayoutParams = new LinearLayout.LayoutParams(
				LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT);
		buttonLayoutParams = new RadioGroup.LayoutParams(320 / 5,
				RadioGroup.LayoutParams.FILL_PARENT);

		changeTabIntentFilter = new IntentFilter(
				Const.Broadcast.ACTION_CHANGE_TAB);
		changeTabBroadcastReceiver = new ChangeTabBroadcastReceiver();
		registerReceiver(changeTabBroadcastReceiver, changeTabIntentFilter);
	}

	public void onResume() {
		super.onResume();
	}

	public void onPause() {
		super.onPause();
	}

	public void onStop() {

		if (changeTabBroadcastReceiver != null) {
			unregisterReceiver(changeTabBroadcastReceiver);
		}
		
		super.onStop();
	}

	public void commit() {
		bottomRadioGroup.removeAllViews();

		int optimum_visible_items_in_portrait_mode = 5;
		try {
			WindowManager window = getWindowManager();
			Display display = window.getDefaultDisplay();
			int window_width = display.getWidth();

			optimum_visible_items_in_portrait_mode = (int) (window_width / 64.0);
		} catch (Exception e) {
			optimum_visible_items_in_portrait_mode = 5;
		}

		int screen_width = getWindowManager().getDefaultDisplay().getWidth();
		int width;
		if (intentList.size() <= optimum_visible_items_in_portrait_mode) {
			width = screen_width / intentList.size();
		} else {
			// width = screen_width/5;
			width = 320 / 5;
		}

		TabBarButtonDrawable.width = width;
		TabBarButtonDrawable.height = (int) TypedValue.applyDimension(
				TypedValue.COMPLEX_UNIT_DIP, 57, getResources()
						.getDisplayMetrics());
		buttonLayoutParams = new RadioGroup.LayoutParams(width,
				RadioGroup.LayoutParams.FILL_PARENT);

		for (int i = 0; i < intentList.size(); i++) {
			TabBarButton tabButton = new TabBarButton(this);
			int[] iconStates = (int[]) states.get(i);
			tabButton.setState(titleList.get(i), iconStates[0], iconStates[1]);
			tabButton.setId(i);
			tabButton.setGravity(Gravity.CENTER);
			bottomRadioGroup.addView(tabButton, i, buttonLayoutParams);
		}

		setCurrentTab(0);
	}

	public void setTabButtonNotifcation(int tabIndex, int noteImageId) {
		TabBarButton tabButton = (TabBarButton) bottomRadioGroup
				.getChildAt(tabIndex);
		int[] iconStates = (int[]) states.get(tabIndex);
		tabButton.setState(titleList.get(tabIndex), iconStates[0],
				iconStates[1], noteImageId);
		tabButton.invalidate();
	}

	/**
	 * <b><i>protected void addTab(String title, int offIconStateId, int
	 * onIconStateId, Intent intent)</i></b>
	 * <p>
	 * <p>
	 * Add a tab to the navigation bar by specifying the title, 1 image for
	 * button on-state, and 1 image for button off-state
	 * <p>
	 * 
	 * @param title
	 *            a String that specifies that title of the tab button
	 * @param onIconStateId
	 *            id of the on-state image
	 * @param offIconStateId
	 *            id of the off-state image
	 * @param intent
	 *            intent to start when button is tapped
	 */
	protected void addTab(String title, int offIconStateId, int onIconStateId,
			Intent intent) {
		int[] iconStates = { onIconStateId, offIconStateId };
		states.add(iconStates);
		intentList.add(intent);
		titleList.add(title);
	}

	public void onCheckedChanged(RadioGroup group, int checkedId) {
		try {
			if (delegate != null)
				delegate.onTabChanged(checkedId);
		} catch (Exception e) {
		}

		setCurrentTab(checkedId);
	}

	public View startGroupActivity(String id, Intent intent) {
		contentViewLayout.removeAllViews();

		View view = activityManager.startActivity(id, intent).getDecorView();
		contentViewLayout.addView(view, contentViewLayoutParams);

		return view;
	}

	public View setCurrentTab(int index) {
		nCurrentIndex = index;

		bottomRadioGroup.check(index);
		View v = startGroupActivity(titleList.get(index).toString(),
				(Intent) intentList.get(index));
		mapTabView.put(index, v);

		return v;
	}

	public Activity getCurrentActivity() {
		return activityManager.getCurrentActivity();
	}

	public int getCurrentTab() {
		return bottomRadioGroup.getCheckedRadioButtonId();
	}

	public int getCurrentTabIndex() {
		return nCurrentIndex;
	}

	/*
	 * gets required R, not used
	 */
	public boolean inflateXMLForContentView() {
		return false;
	}

	public int bottomBar() {
		return -1;
	}

	public void setDelegate(SliderBarActivityDelegate delegate_) {
		delegate = delegate_;
	}

	public static abstract class SliderBarActivityDelegate {

		protected void onTabChanged(int tabIndex) {
		}
	}

	/*
	 * Broadcast receiver to set current tab
	 */
	public class ChangeTabBroadcastReceiver extends BroadcastReceiver {
		@Override
		public void onReceive(Context context, Intent intent) {

			@SuppressWarnings("unused")
			String action = intent.getAction();

			Bundle bundle = intent.getExtras();
			int nIndex = bundle.getInt(Const.Broadcast.CURRENT_TAB_INDEX);
			setCurrentTab(nIndex);

			/*
			 * int nSubIndex = bundle.getInt(Const.CURRENT_SUBTAB_INDEX); int
			 * nShareId = bundle.getInt("fileid");
			 * 
			 * Intent bIntent = new Intent(Const.ACTION_CHANGE_SUBTAB);
			 * bIntent.putExtra(Const.CURRENT_SUBTAB_INDEX, nSubIndex);
			 * bIntent.putExtra("fileid", nShareId); sendBroadcast(bIntent);
			 */
		}

	}
}
